<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\ExamineRecord;
use addons\qingdong\model\FormField;
use addons\qingdong\model\Message;
use addons\qingdong\model\Receivables as ReceivablesModel;
use addons\qingdong\model\ReceivablesOther;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Staff;
use think\Db;
use think\Exception;

/**
 * 回款详情
 */
class Receivables extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//新增回款
	public function addReceivables() {
		$params = $this->request->post();

		// 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }

        $result = FormField::checkFields(FormField::RECEIVABLES_TYPE, $params);
        if ($result !== true) {
            $this->error($result);
        }
		if (ReceivablesModel::where(['number' => $params['number'], 'contract_id' => $params['contract_id']])->find()) {
			$this->error('回款编号已存在');
		}
		$contract=Contract::where(['id'=>$params['contract_id']])->find();
		if(empty($contract)){
			$this->error('合同不存在');
		}
		if($contract['check_status'] != 2){
			$this->error('当前合同未审核通过');
		}
		Db::startTrans();
		try {
            $params['owner_staff_id'] = $contract['owner_staff_id'];

			ReceivablesModel::createReceivables($params);

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('新增回款成功');
		}
	}


	//获取回款列表
    public function getList()
    {
        $customer_id = input('customer_id');
        $contract_id = input('contract_id');
        $times = input('times');
        $staff_id = input('staff_id');
        $check_status = input('check_status');
        $limit = input('limit');
        $type = input('type',0);
        $params=input();
        $where= FormField::updateWhereField(FormField::RECEIVABLES_TYPE,$params);
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($contract_id) {
            $where['contract_id'] = $contract_id;
        }
        if ($staff_id) {
            $where['owner_staff_id'] = $staff_id;
        } else {

            if ($type == 1) {//我的客户
                $where['owner_staff_id'] = $this->auth->id;
            } elseif ($type == 2) {//下属负责的客户
                $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            }else{
                $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            }
        }

        if ($times) {//回款日期
            $times = explode(',', $times);
            $where['return_time'] = ['between', [$times[0], $times[1]]];
        }
        if ($check_status) {
            if ($check_status == 1) {//审核中
                $where['check_status'] = ['in', [0, 1]];
            } elseif ($check_status == 2) {//审核通过
                $where['check_status'] = 2;
            } elseif ($check_status == 3) {//其他
                $where['check_status'] = ['in', [3, 4]];
            }
        }
        $list = ReceivablesModel::where($where)->with(['contract'])->order('id desc')->paginate($limit)->toArray();

        $remoney = ReceivablesModel::where(['owner_staff_id'=>$where['owner_staff_id']])
            ->where(array('check_status'=>2))->sum('money');
        $inmoney = ReceivablesModel::where(['owner_staff_id'=>$where['owner_staff_id']])
            ->where(array('check_status'=>['in',[0,1]]))->sum('money');
        $nomoney = ReceivablesModel::where(['owner_staff_id'=>$where['owner_staff_id']])
            ->where(array('check_status'=>['in',[3,4]]))->sum('money');
        $moneyinfo['remoney'] = $remoney;//已回款
        $moneyinfo['inmoney'] = $inmoney;//回款中
        $moneyinfo['nomoney'] = $nomoney;//未回款
        $moneyinfo['allmoney'] = $remoney+$inmoney+$nomoney;//总金额
        $list['moneyinfo']=$moneyinfo;
        $this->success('请求成功',$list);
    }


	//回款详情
	public function getDetail() {
		$id       = input('id');
		$receivables = ReceivablesModel::where(['id' => $id])->with([
			'customer',
			'contract',
			'plan',
			'ownerStaff',
			'createStaff'
		])->find();

		if (empty($receivables)) {
            //标记通知已读
            Message::setRead(Message::RECEIVABLES_TYPE, $id, $this->auth->id);
			$this->error('信息不存在');
		}
		$receivables=$receivables->toArray();

        $receivables=ReceivablesOther::getOther($receivables);
		//标记通知已读
		Message::setRead(Message::RECEIVABLES_TYPE, $id, $this->auth->id);
		$this->success('请求成功', $receivables);
	}


	//撤回审核
	public function cancel() {
		$id       = input('id');
		$customer = ReceivablesModel::where(['id' => $id, 'check_status' => 1])->find();
		if (empty($customer)) {
			$this->error('回款信息不存在');
		}
		Db::startTrans();
		try {

			ReceivablesModel::where(['id' => $id])->update(['check_status' => 4]);
			ExamineRecord::where([
				'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
				'relation_id'   => $id,
				'status'        => 0
			])->update(['status' => 3]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();;
			$this->error($e->getMessage());
		}


		$this->success('撤回成功');
	}


	//修改回款
	public function editReceivables() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ReceivablesModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
		if (empty($row)) {
			$this->error('回款信息不存在');
		}
		// 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::RECEIVABLES_TYPE, $params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		Db::startTrans();
		try {
			ReceivablesModel::updateReceivables($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		$this->success('修改回款信息成功');
	}
    //获取回款编号
    public function getReceivablesNumber()
    {
        $this->success('请求成功', ['number' => ReceivablesModel::getNum()]);
    }
}
